<template>
    <div class="memorialManage-container">
        
		<el-main class="memorialManage-main">
            <div class="page-wrapper">
                <div class="container">
                    <!-- 页面头部 -->
                    <header class="page-header">
                        <span class="title">创建家族馆</span>
                        <button class="back-btn" @click="goBack">返回上一页</button>
                    </header>

                    <!-- 主内容区域 -->
                    <main class="main-content">
                        <div class="form-container">
                            <!-- 左侧表单 -->
                            <div class="form-left">
                                <form @submit.prevent="handleSubmit">
                                    <div class="form-row">
                                        <label for="hallName">家族馆LOGO：</label>
                                        <div class="input-wrapper">
                                            <el-upload
                                                class="avatar-uploader"
                                                :action="upLoadUrl"
                                                :show-file-list="false"
                                                :on-success="handleAvatarSuccess"
                                                :before-upload="beforeAvatarUpload"
                                            >
                                                <img v-if="form.logo" :src="form.logo" class="avatar" />
                                                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                                            </el-upload>
                                        </div>
                                    </div>
                                    <!-- 家族馆名称 -->
                                    <div class="form-row">
                                        <label for="hallName">家族馆名称：</label>
                                        <div class="input-wrapper">
                                            <input type="text" id="hallName" v-model="form.name" />
                                        </div>
                                    </div>

                                    <!-- 导语 -->
                                    <div class="form-row">
                                        <label for="prologue">导语：</label>
                                        <div class="input-wrapper">
                                            <textarea id="prologue" v-model="form.intro" rows="4"></textarea>
                                            <span class="hint">建议少于80字</span>
                                        </div>
                                    </div>

                                    <!-- 落款 -->
                                    <div class="form-row">
                                        <label for="signature">落款：</label>
                                        <div class="input-wrapper">
                                            <textarea id="signature" v-model="form.inscribe" rows="2"></textarea>
                                            <span class="hint">建议少于30字</span>
                                        </div>
                                    </div>

                                    <!-- 家族馆简介 -->
                                    <div class="form-row">
                                        <label for="description">家族馆简介：</label>
                                        <div class="input-wrapper">
                                            <textarea id="description" v-model="form.desc" rows="6"></textarea>
                                        </div>
                                    </div>
                                    <div class="form-row">
                                        <label for="description">创建人署名：</label>
                                        <div class="input-wrapper">
                                            <input type="text" id="creator" v-model="form.sign_name" readonly />
                                        </div>
                                    </div>
                                </form>
                            </div>

                            <!-- 右侧样式示例 -->
                            <div class="form-right">
                                <div class="style-example" @click="showStyleDialog = true">
                                    <img :src="selectedStyleImage" alt="样式示例图片" v-if="form.template_id !== 0"/>
                                    <img src="https://cqjsyh.com/uploads/images/20250709/202507092119562bf858482.png" alt="样式示例图片" v-else/>
                                    <div class="caption">样式示例</div>
                                </div>
                            </div>
                        </div>

                        <!-- 创建人署名 (跨列) -->
                        <!-- <div class="form-row full-width-row">
                            <label for="creator">创建人署名：</label>
                            <div class="input-wrapper">
                                <input type="text" id="creator" v-model="form.sign_name" readonly />
                            </div>
                        </div> -->

                        <!-- 提交和返回按钮 -->
                        <div class="action-buttons">
                            <button class="submit-btn" @click="handleSubmit">提 交</button>
                            <button class="return-btn" @click="goBack">返 回</button>
                        </div>
                    </main>

                    <!-- 底部提示信息 -->
                    <footer class="page-footer">
                        <p>今生永恒网郑重提示：纪念净地，敬请保持肃穆！切莫发布与纪念主题不符、违法及广告等信息，发表人须承担一切因其行为而直接或间接导致的民事或刑事法律责任。本站保留追究法律责任的权利！</p>
                    </footer>
                </div>
            </div>
		</el-main>

        <!-- 样式选择弹窗 -->
        <el-dialog v-model="showStyleDialog" title="选择样式模板" width="800px" center>
            <div class="style-gallery">
                <div 
                    v-for="(style, index) in templateData" 
                    :key="index" 
                    class="style-item"
                    @click="selectStyle(style)"
                    :class="{ active: form.template_id === style.id }"
                >
                    <img :src="style.bgImgUrl" />
                    <!-- <div class="style-name">{{ style.name }}</div> -->
                     <el-button type="primary" link @click="previewImageFun(style.bgImgUrl)">预览</el-button>
                </div>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="showStyleDialog = false">取消</el-button>
                    <el-button type="primary" @click="confirmStyleSelection">确定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 图片预览弹窗 -->
        <el-dialog v-model="showPreviewDialog" title="图片预览" width="600px" center>
            <div class="preview-container">
                <img :src="previewImage" alt="预览图片" class="preview-image" />
            </div>
        </el-dialog>
        
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, toRaw } from 'vue';
import Header from '@/components/header/index.vue';
import Footer from '@/components/footer/index.vue';
import type { FormInstance, UploadProps, FormRules } from 'element-plus'
import useUserStore from '@/stores/modules/user'
const userStore = useUserStore()
import { useRouter, useRoute } from 'vue-router'
const router = useRouter();
const route = useRoute();
type ViewMode = string;
const viewMode = ref<ViewMode>('family'); // 当前视图状态 ('list' 或 'detail')
// 定义数据结构类型
import { familyAdd, familyEdit, familyDetail, familyMyList, familyJoinList } from '@/api/family';
// 使用 reactive 创建一个响应式的表单数据对象
const form = reactive({
    id: '',
    logo:'',
    name: '',
    intro: '',
    desc: '',
    inscribe: '',
    sign_name: userStore.userInfo.real_name, // 根据图片，创建人是预设且只读的
    type: 1,
    template_id: 0
});

// 弹窗状态管理
const showStyleDialog = ref(false);
const showPreviewDialog = ref(false);
const previewImage = ref('');
const selectedStyleImage = ref('https://via.placeholder.com/200x150/8B4513/FFFFFF?text=经典风格'); // 默认样式图片
const tempSelectedStyle = ref('');

// 样式模板数据
const styleTemplates = ref([
    {
        name: '经典风格',
        image: 'https://via.placeholder.com/200x150/8B4513/FFFFFF?text=经典风格'
    },
    {
        name: '现代简约',
        image: 'https://via.placeholder.com/200x150/4169E1/FFFFFF?text=现代简约'
    },
    {
        name: '古典雅致',
        image: 'https://via.placeholder.com/200x150/8B0000/FFFFFF?text=古典雅致'
    },
    {
        name: '温馨家庭',
        image: 'https://via.placeholder.com/200x150/FF69B4/FFFFFF?text=温馨家庭'
    },
    {
        name: '庄重肃穆',
        image: 'https://via.placeholder.com/200x150/2F4F4F/FFFFFF?text=庄重肃穆'
    }
]);
// 模版数据
const templateData = ref(
  [
    { id: 1, bgImgUrl: 'https://cqjsyh.com/uploads/images/20250709/20250709204046b91ea1033.png' },
    { id: 2, bgImgUrl: 'https://cqjsyh.com/uploads/images/20250709/20250709204438f8c397688.png' },
    { id: 3, bgImgUrl: 'https://cqjsyh.com/uploads/images/20250709/20250709204458ad8c05876.png' },
    { id: 4, bgImgUrl: 'https://cqjsyh.com/uploads/images/20250709/2025070920451229ffc4763.png' },
    { id: 5, bgImgUrl: 'https://cqjsyh.com/uploads/images/20250709/20250709204532f70845720.png' },
  ]
)
// 提交表单的处理函数
const handleSubmit = async () => {
    // 在真实应用中，这里会调用 API 发送数据到后端
    console.log('表单已提交:', form);
    // alert('表单已提交！请在控制台查看数据。');
    await familyEdit(form)
    window.history.back();
};

// 返回上一页的函数
const goBack = () => {
    // 简单地使用浏览器的 history API
    window.history.back();
};

// 上传图片
const upLoadUrl = import.meta.env.VITE_APP_BASE_URL + '/api/upload/image'
const imageUrl = ref('')

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
    console.log(response, toRaw(uploadFile))
    // form.logo = URL.createObjectURL(uploadFile.raw!)
    form.logo = response.data.uri
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('只能上传jpg/png文件!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('文件大小不能超过 2MB!')
    return false
  }
  return true
}

// 选择样式处理函数
const selectStyle = (style: any) => {
    form.template_id = style.id
    tempSelectedStyle.value = style.bgImgUrl;
    // 点击图片预览
    // previewImage.value = style.bgImgUrl;
    // showPreviewDialog.value = true;
};

// 预览事件
const previewImageFun = (url: string) => {
    previewImage.value = url;
    showPreviewDialog.value = true;
};

// 确认样式选择
const confirmStyleSelection = () => {
    if (tempSelectedStyle.value) {
        selectedStyleImage.value = tempSelectedStyle.value;
    }
    showStyleDialog.value = false;
};
// 获取家族详情
const getFamilyDetail = async () => {
    const id = route.query.id
    const res = await familyDetail({id})
    console.log(res)
    form.name = res.name
    form.intro = res.intro
    form.desc = res.desc
    form.inscribe = res.inscribe
    form.logo = res.logo
    form.id = res.id

    form.template_id = res.template_id

    if(res.template_id){
        selectedStyleImage.value = templateData.value.find(item => item.id === res.template_id)?.bgImgUrl || ''
    }
}
onMounted(() => {
    getFamilyDetail()
    form.type = Number(route.query.type)
})
</script>

<style scoped>
.memorialManage-container {
	/* padding: 20px; */
	background: #f8f8f8;
}



.sidebar {
	background: #fff;
}

.menu-card {
	padding: 10px 0;
}

.menu-title {
	width: 100%;
	display: flex;
	align-items: center;
	justify-content: center;
	font-weight: bold;
	margin-bottom: 10px;
	cursor: pointer;
}
.menu-title:hover {
	color: #F16C20;
}
.menu-item {
	font-weight: bold;
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin: 10px 0;
	cursor: default;
	font-weight: 500;
	border-top: #ccc 1px dotted;
	background: #F5F5F5;
    color: #666;
}

.sub-menu {
	padding-left: 12px;
	font-size: 14px;
	color: #666;
	margin: 5px 0;
	cursor: pointer;
}
.sub-menu:hover {
	color: #F16C20;
}



.memorialManage-main {
	width: 100%;
	max-width: 1200px;
	margin: 0 auto;
}
/* 使用常见的中文网站字体 */
.management-panel {
    font-family: "Microsoft YaHei", "SimSun", sans-serif;
    background-color: #ffffff;
    /* 确保背景是白色 */
    color: #333;
    width: 100%;
    /* 组件宽度自适应父容器 */
    max-width: 950px;
    /* 设定一个最大宽度以匹配图片观感 */
}





/* 使用宋体来还原复古感 */
* {
    font-family: 'SimSun', '宋体', serif;
}

/* 页面包裹层，设置灰色背景 */
.page-wrapper {
    background-color: #f2f3f5;
    padding: 20px;
    min-height: 100vh;
}

/* 主容器，限制最大宽度并居中 */
.container {
    margin: 0 auto;
}

/* 页面头部 */
.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 2px solid #E89F48;
    padding-bottom: 8px;
    margin-bottom: 20px;
}

.page-header .title {
    background-color: #E89F48;
    color: white;
    padding: 5px 15px;
    font-size: 14px;
    font-weight: bold;
}

.page-header .back-btn {
    background-color: #E89F48;
    color: white;
    border: none;
    padding: 5px 15px;
    font-size: 12px;
    cursor: pointer;
}

/* 主内容白色区域 */
.main-content {
    background-color: #ffffff;
    border: 1px solid #DCDCDC;
    padding: 30px;
}

.form-container {
    display: flex;
    gap: 20px;
    /* 左右两栏的间距 */
}

.form-left {
    flex: 1;
    /* 占据剩余空间 */
}

.form-right {
    width: 230px;
    /* 固定右侧宽度 */
    flex-shrink: 0;
}

/* 表单行样式 */
.form-row {
    display: flex;
    margin-bottom: 15px;
    align-items: flex-start;
    /* 标签和输入框顶部对齐 */
}

.form-row label {
    width: 100px;
    /* 固定标签宽度 */
    text-align: right;
    padding-right: 10px;
    font-size: 14px;
    color: #333;
    padding-top: 5px;
    /* 微调使标签垂直居中 */
    flex-shrink: 0;
}

/* 使用全角空格进行对齐 */
.form-row label {
    white-space: pre;
}


.input-wrapper {
    flex-grow: 1;
    position: relative;
}

/* 输入框和文本域的通用样式 */
input[type="text"],
textarea {
    width: 100%;
    border: 1px solid #767676;
    padding: 5px;
    font-size: 14px;
    box-sizing: border-box;
    /* 保证 padding 不会撑大宽度 */
    resize: vertical;
    /* 允许垂直缩放 */
}

textarea {
    resize: none;
    /* 禁用缩放，与图片保持一致 */
}

/* 只读输入框的样式 */
input[readonly] {
    background-color: #f0f0f0;
    color: #555;
}

/* 输入提示文字 */
.input-wrapper .hint {
    position: absolute;
    bottom: 8px;
    right: 10px;
    font-size: 12px;
    color: #999;
    background-color: #fff;
    /* 遮盖 textarea 的边框 */
    padding: 0 2px;
}

/* 创建人署名是单独一行，占满宽度 */
.full-width-row .input-wrapper {
    width: 400px;
    /* 根据图片目测宽度 */
}

/* 右侧样式示例 */
.style-example {
    background-color: #4F260E;
    padding: 10px;
    border: 1px solid #ccc;
}

.style-example img {
    width: 100%;
    display: block;
}

.style-example .caption {
    background-color: #6A3B1C;
    color: white;
    text-align: center;
    padding: 8px 0;
    margin-top: 10px;
    font-size: 14px;
}

/* 操作按钮区域 */
.action-buttons {
    margin-top: 25px;
    margin-left: 100px;
    /* 与表单标签对齐 */
}

/* 模拟复古的按钮样式 */
.submit-btn,
.return-btn {
    width: 80px;
    height: 30px;
    background-color: #f0f0f0;
    border: 1px solid #888;
    cursor: pointer;
    font-size: 14px;
    color: #333;
    /* 关键：使用内外边框颜色不同来创建3D/浮雕效果 */
    border-top: 1px solid #fff;
    border-left: 1px solid #fff;
    border-right: 1px solid #888;
    border-bottom: 1px solid #888;
}

.submit-btn:active,
.return-btn:active {
    /* 按下时反转边框颜色，产生内陷效果 */
    border-top: 1px solid #888;
    border-left: 1px solid #888;
    border-right: 1px solid #fff;
    border-bottom: 1px solid #fff;
}

.return-btn {
    margin-left: 15px;
}

/* 底部提示信息 */
.page-footer {
    margin-top: 20px;
    padding: 15px;
    border-top: 1px solid #e0e0e0;
}

.page-footer p {
    font-size: 12px;
    color: #666;
    line-height: 1.8;
    text-align: justify;
}


.avatar-uploader{
        border: 1px dashed #cdd0d6;
        border-radius: 6px;
        overflow: hidden;
        width: 100px;
        height: 100px;
        box-sizing: border-box;
    }
    .avatar-uploader .avatar {
        width: 100px;
        height: 100px;
        display: block;
        object-fit: contain;
    }

    .avatar-uploader .el-upload {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
    }

    .avatar-uploader .el-upload:hover {
        border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 100px;
        height: 100px;
        text-align: center;
    }

/* 样式选择弹窗样式 */
.style-gallery {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 20px;
    padding: 20px 0;
}

.style-item {
    border: 2px solid #ddd;
    border-radius: 8px;
    overflow: hidden;
    cursor: pointer;
    transition: all 0.3s ease;
    text-align: center;
}

.style-item:hover {
    border-color: #409eff;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.style-item.active {
    border-color: #409eff;
    background-color: #f0f9ff;
}

.style-item img {
    width: 100%;
    height: 120px;
    object-fit: cover;
    display: block;
}

.style-name {
    padding: 10px;
    font-size: 14px;
    color: #333;
    background-color: #fff;
}

.style-item.active .style-name {
    color: #409eff;
    font-weight: bold;
}

/* 图片预览弹窗样式 */
.preview-container {
    text-align: center;
    padding: 20px;
}

.preview-image {
    max-width: 100%;
    max-height: 400px;
    object-fit: contain;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 样式示例区域增加点击提示 */
.style-example {
    cursor: pointer;
    transition: all 0.3s ease;
    position: relative;
}

.style-example:hover {
    transform: scale(1.02);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.style-example:hover::after {
    content: '点击选择样式';
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: rgba(0, 0, 0, 0.7);
    color: white;
    padding: 8px 12px;
    border-radius: 4px;
    font-size: 12px;
    white-space: nowrap;
    z-index: 10;
}
</style>